package lab.anoper.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 闫家洪（yanjiahong@vcredit.com）
 * @since 2024/12/11
 */
public class ReentrantLockExample {

    // 创建一个 ReentrantLock 对象
    private final Lock lock = new ReentrantLock();

    private int count = 0;

    // 增加计数
    public void increment() {
        lock.lock(); // 获取锁
        try {
            count++; // 修改共享变量
            System.out.println("Count after increment: " + count);
        } finally {
            lock.unlock(); // 确保释放锁
        }
    }

    // 获取当前计数
    public int getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockExample example = new ReentrantLockExample();

        // 创建多个线程并执行
        Thread t1 = new Thread(example::increment);
        Thread t2 = new Thread(example::increment);
        Thread t3 = new Thread(example::increment);

        t1.start();
        t2.start();
        t3.start();

        try {
            // 等待线程结束
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出最终计数
        System.out.println("Final count: " + example.getCount());
    }
}
